import os
import tempfile
from tools.download import rpm
from tools.parse import parse
from tools.splitter.splitter import _architecture_check, _clone_slices
from tools.logger import logger
from tools import SLICE_PATH

from tools.generator import classifier
from tools.generator.dependency_analyzer import DependencyAnalyzer
from tools.generator.writer import SDFWriter


class SDFGenerator:
    """Class to generate SDF files for a given package."""

    # Class attributes for the generator
    package: str
    release: str
    arch: str
    output: str

    def __init__(self, release: str, arch: str, output: str, package: str):
        self.release = f"openEuler-{release.upper()}"
        self.arch = _architecture_check(arch)
        self.output = os.path.abspath(output)
        self.package = package

    def gen(self):
        """
        Main entry point for generating SDF files.
        """
        logger.info(f"===== Starting SDF Generation for: {self.package} =====")

        _clone_slices(self.release, SLICE_PATH)

        # Initialize DNF client for downloading
        logger.info(f"Downloading package: {self.package}...")
        dnf_client = rpm.init_dnf_client(self.arch, self.release, self.output)
        local_pkg_path = rpm.download(dnf_client, self.package)
        if not local_pkg_path:
            logger.error(f"Failed to download package {self.package}.")
            rpm.clear(dnf_client)
            return
        logger.info(f"Package downloaded to: {local_pkg_path}")

        # extracting RPM files
        pkg_root_dir = tempfile.TemporaryDirectory()
        logger.info(f"Extracting {local_pkg_path} to {pkg_root_dir} for analysis...")
        parse.extract_files(local_pkg_path, pkg_root_dir.name, ["/*"])

        # Classify files into slices
        classified_slices = classifier.classify_files(self.package, pkg_root_dir.name)
        for slice_name, files in classified_slices.items():
            logger.info(f"Slice '{slice_name}' contains {files} ")

        # Analyze dependencies
        analyzer = DependencyAnalyzer(self.package, pkg_root_dir.name, classified_slices)
        slice_deps = analyzer.analyze()
        for slice_name, deps in slice_deps.items():
            logger.info(f"Slice '{slice_name}' depends on: {deps}")

        # Write the SDF file
        writer = SDFWriter(self.output, self.package, classified_slices, slice_deps)
        writer.write()

        rpm.clear(dnf_client)

        logger.info(f"===== Finished SDF Generation for: {self.package} =====")
